package com.pnnd.utils;

import java.lang.reflect.Array;

public class ArrayUtils {

    private ArrayUtils(){

    }

    public static IntTuple getShape(Object array){

        if(array == null){
            throw new NullPointerException();
        }

        if(!array.getClass().isArray()){
            throw new NotArrayClassException(array.getClass());
        }

        int tupleSize = 1;

        Class<?> itemClass = array.getClass().getComponentType();

        while(itemClass.isArray()){
            tupleSize += 1;
            itemClass = itemClass.getComponentType();
        }

        int[] shapeValues = new int[tupleSize];

        Object arrayObj = array;

        for(int i=0;i<tupleSize;i++){
            shapeValues[i] = Array.getLength(arrayObj);

            if(shapeValues[i] != 0 && i!=tupleSize -1){
                arrayObj = Array.get(arrayObj,0);

                if(arrayObj == null){
                    throw new HasNullDimException(array,i);
                }
            }
        }

        return new IntTuple(shapeValues);
    }

    public static void main(String[] args){


        Object o = Array.newInstance(int.class,3,2,3);

        System.out.println(o.getClass().toString());

        System.out.println(ArrayUtils.getShape(o));
    }

}
